package ms.pay.app.alibaba;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;

import javax.servlet.http.HttpServletRequest;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import static com.alipay.api.AlipayConstants.CHARSET;

/**
 * Project Name: ms
 * File Name: Alipay
 * Package Name: ms.pay.app.alibaba.pay
 * Date: 2018/5/11  10:51
 * Copyright (c) 2018, tianyul All Rights Reserved.
 */
public class Alipay {

    private Alipay() {
    }

    /**
     * 获取ios 或 android 端所需要的支付宝支付信息
     * @param alipayParam
     * @return
     */
    public static String getOrderString(AlipayParam alipayParam) {
        //实例化客户端
        AlipayClient alipayClient = new DefaultAlipayClient(alipayParam.getServerUrl(), alipayParam.getAppId(), alipayParam.getPrivateKey(), "json", CHARSET, alipayParam.getAlipayPublicKey(), "RSA2");
        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        model.setBody(alipayParam.getBody());
        model.setSubject(alipayParam.getSubject());
        model.setOutTradeNo(alipayParam.getOrderId());
        model.setTimeoutExpress(alipayParam.getTimeoutExpress());
        model.setTotalAmount(alipayParam.getTotalAmount());
        model.setProductCode("QUICK_MSECURITY_PAY");
        request.setBizModel(model);
        request.setNotifyUrl(alipayParam.getNotifyUrl());
        try {
            //这里和普通的接口调用不同，使用的是sdkExecute
            AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
            System.out.println(response.getBody());//就是orderString 可以直接给客户端请求，无需再做处理。
            return response.getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 根据回调请求校验参数并返回关键数据
     * @param request
     * @param alipayPublicKey  支付宝公钥
     * @return  null 说明校验失败    有数据就是校验成功
     */
    public Map<String,Object> checkRequestParam(HttpServletRequest request, String alipayPublicKey) {
        Map<String,Object> result = new HashMap<>();
        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        //切记alipaypublickey是支付宝的公钥，请去open.alipay.com对应应用下查看。
        //boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
        try {
            boolean flag = AlipaySignature.rsaCheckV1(params, alipayPublicKey, CHARSET, "RSA2");
            if(flag) {//校验成功
                if("TRADE_SUCCESS".equals(params.get("trade_status"))){
                    //付款金额
                    String amount = params.get("buyer_pay_amount");
                    //商户订单号
                    String out_trade_no = params.get("out_trade_no");
                    //支付宝交易号
                    String trade_no = params.get("trade_no");
                    //附加数据
                    String passback_params = URLDecoder.decode(params.get("passback_params"));

                    result.put("amount", amount);//金额
                    result.put("orderId", out_trade_no);//订单id
                    result.put("tradeNo", trade_no);//支付宝交易号
                    result.put("params", passback_params);//附加数据

                    return result;
                }
            }
            return null;
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return null;
        }
    }
}
